<?php

namespace app\api\controller\order;

use think\Controller;

class Order extends Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->TypeModel = model('Product.Type');
        $this->ProductModel = model('Product.Product');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
        $this->AddressModel = model('User.Address');
        $this->VipModel = model('Product.Vip');
        $this->CartModel = model('Cart');
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->ContactTypeModel = model('Contact.Type');
        $this->AdminsModel = model('Admin');
        $this->PayModel = model('Pay');
    }

    // 生成订单
    public function add()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $addrid = $this->request->param('addrid', 0);
            $cartids = $this->request->param('cartids', '');
            $content = $this->request->param('content', '');

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $address = $this->AddressModel->where(['userid' => $userid, 'id' =>  $addrid])->find();

            if (!$address) {
                $this->error('收货地址不存在，请重新选择');
                exit;
            }

            $where = [
                'cart.id' => ['in', $cartids],
                'userid' => $userid
            ];

            // 查询购物车的产品数据
            $cartlist = $this->CartModel->with('product')->where($where)->select();

            if (!$cartlist) {
                $this->error('下单数据为空，请重新选择商品');
                exit;
            }

            //判断商品库存是否充足
            foreach ($cartlist as $item) {

                //购物车的数量 和商品的库存
                $nums = $item['nums'];
                $stock = $item['product']['stock'];

                //让库存 - 购物车数量 精确计算bcsub
                $pronums = bcsub($stock, $nums);

                if ($pronums < 0) {

                    $this->error($item['product']['name'] . "库存不足，请重新选择");
                    exit;
                }
            }

            //查询下单数据的总价格条件
            $sumtotal = [
                'id' => ['in', $cartids],
                'userid' => $userid,
            ];

            //查询下单数据的总价格
            $total = $this->CartModel->where($sumtotal)->sum('total');

            //用户积分
            $point = $userinfo['point'];

            // 判断用户积分够不够
            $UpdatePoint = bcsub($point, $total);

            if ($UpdatePoint < 0) {

                $this->error('积分不足，请充值后操作');
                exit;
            }

            // 开启事条
            //订单表(INSERT) 订单商品表(INSERT) 商品库存(update) 用户积分(update) 消费记录(insert) 购物车(delete)

            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CartModel->startTrans();


            //组装订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code("AK"),  //ask => AK
                'content' => $content,
                'status' => 1,
                'total' => $total
            ];

            //订单表
            $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            }


            // $orderid = $this->OrderModel->id;

            // 订单商品表插入
            $OrderProductData = [];
            $ProductData = [];

            foreach ($cartlist as $item) {
                //订单商品
                $OrderProductData[] = [
                    'orderid' => $this->OrderModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];

                //商品库存 - 购物车数量
                $stock = bcsub($item['product']['stock'], $item['nums']);

                //商品库存
                $ProductData[] = [
                    'id' => $item['proid'],
                    'stock' => $stock,
                ];
            }

            //插入订单商品表
            $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if ($OrderProductStatus === FALSE) {
                //回滚
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

            //商品更新库存
            $ProductStatus = $this->ProductModel->isUpdate()->saveAll($ProductData);

            if ($ProductStatus === FALSE) {
                //回滚
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }


            // 用户积分
            $UserStatus = $this->UserModel->isUpdate()->save(['id' => $userid, 'point' => $UpdatePoint]);

            if ($UserStatus === FALSE) {
                //回滚
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData = [
                'point' => $total,
                'content' => "订单号：" . $OrderData['code'] . "---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid
            ];
            // 插入消费记录表
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if ($RecordStatus === FALSE) {
                //回滚
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 购物车
            $CartStatus = $this->CartModel->destroy($cartids);

            if ($CartStatus === FALSE) {
                //回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->CartModel->getError());
                exit;
            }

            if ($OrderStatus !== FALSE && $OrderProductStatus !== FALSE && $ProductStatus !== FALSE && $UserStatus !== FALSE && $RecordStatus !== FALSE && $CartStatus !== FALSE) {
                //提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->CartModel->commit();

                $this->success('下单成功，等待商家发货', '/user/order/index');
                exit;
            } else {
                //回滚
                $this->CartModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('下单失败,请重新操作');
                exit;
            }
        }
    }

    // 订单列表/消費
    public function list()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', 0);
            // 消费状态
            $consump = $this->request->param('consump', false);
            // 页码
            $start = $this->request->param('start', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $where = [];
            // 判断订单类型
            if ($status != 0) {
                $where['status'] = $status;
            }

            $where['userid'] = $userid;

            // 订单信息
            if ($consump) {
                $result = $this->OrderModel->where($where)->order('createtime', 'desc')->limit($start, 5)->select();
            } else {
                $result = $this->OrderModel->where($where)->select();
            }

            if (!$result) {
                $this->success('暂无订单数据');
                exit;
            }

            $orderlist = [];
            if (!$consump) {
                foreach ($result as $item) {

                    //组装订单数据
                    $info = [
                        'id' => $item['id'],
                        'code' => $item['code'],
                        'total' => $item['total'],
                        'createtime' => $item['createtime'],
                        'status' => $item['status'],
                        'status_text' => $item['status_text'],
                    ];

                    //获取订单中的第一个商品
                    $product = $this->OrderProductModel->with('info')->where(['orderid' => $item['id']])->find();

                    // 判断订单中产品的结果，第二个是否有这个产品
                    if ($product && $product['info']['id']) {
                        $info['product'] = $product['info'];
                    }
                    $orderlist[] = $info;
                }
            } else {
                // 消费
                foreach ($result as $item) {

                    //组装订单数据
                    $info = [
                        'id' => $item['id'],
                        'code' => $item['code'],
                        'total' => $item['total'],
                        'createtime' => $item['createtime'],
                    ];

                    //获取订单中的第一个商品
                    $product = $this->OrderProductModel->with('info')->where(['orderid' => $item['id']])->find();
                    // 判断订单中产品的结果，第二个是否有这个产品
                    if ($product && $product['info']['id']) {
                        $src = $product['info']['cover_cdn'];
                        $ordername = $product['info']['name'];
                        $orderrice = $product['info']['price'];
                        $info['product'] = "<div class='van-card'>
                        <div class='van-card__header'>
                        <a class='van-card__thumb'>
                        <div class='van-image' style='width: 100%; height: 100%;'>
                        <img src='$src' class='van-image__img' style='object-fit: cover;'>
                        </div>
                        </a>
                        <div class='van-card__content'><div>
                        <div class='van-card__title van-multi-ellipsis--l2'>
                        订单号：$item[code]
                        </div>
                        <div class='van-card__desc van-ellipsis'>
                        商品名称：$ordername
                        </div>
                        <p>下单时间：$item[createtime]</p>
                        </div>
                        <div class='van-card__bottom'>
                        <div class='van-card__price'><div>
                        <span class='van-card__price-currency'>¥</span>
                        <span class='van-card__price-integer'>$orderrice</span>.
                        <span class='van-card__price-decimal'>00</span>
                        </div></div>
                        
                        </div></div></div><div class='van-card__footer'></div></div>
                        ";
                        // <div class='van-card__num'>
                        // <button type='button' class='van-button van-button--default van-button--mini' data-orderid='$item[id]' >
                        // <div class='van-button__content' >
                        //   <span class='van-button__text'>订单详情</span>
                        // </div></button></div>
                    }
                    $orderlist[] = $info;
                }
            }

            $this->success('返回订单数据', null, $orderlist);
            exit;
        }
    }

    // 订单详情
    public function info()
    {

        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $orderinfo = $this->OrderModel->with('express')->find($id);

            if (!$orderinfo) {
                $this->error('订单不存在，请去下单');
                exit;
            }

            //订单商品
            $product = $this->OrderProductModel->with('info')->where(['orderid' => $id])->select();

            //判断订单商品是否存在
            if (!$product) {
                $this->error('订单商品不存在');
                exit;
            }

            //获取订单的收货地址
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->find($orderinfo['addrid']);

            if (!$address) {
                $this->error('未找到订单的收货地址');
                exit;
            }

            $data = [
                'order' => $orderinfo,
                'product' => $product,
                'address' => $address
            ];

            $this->success('返回订单数据成功', null, $data);
            exit;
        }
    }

    // 充值记录
    public function recharge()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            // 页码
            $start = $this->request->param('start', 0);
            //当没有找到用户的情况下
            $userinfo = $this->UserModel->find($userid);
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }
            $where = [
                'userid' => $userid,
                'adminid' => ['neq', 'not null'],
            ];

            // 充值订单信息
            $result = $this->PayModel->where($where)->order('createtime', 'desc')->limit($start, 5)->select();

            if (!$result) {
                $this->success('暂无充值数据');
                exit;
            }

            $this->success('返回订单数据', null, $result);
            exit;
        }
    }

    // 评价
    public function appraise()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0);
            $userid = $this->request->param('userid', 0);
            $comment = $this->request->param('comment', '');
            $appraise = $this->request->param('appraise', 0);
            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }
            $data = [
                'id' => $id,
                'userid' => $userid,
                'status' => 4
            ];
            if ($comment) {
                $data['comment'] = $comment;
            }
            if ($appraise) {
                $data['appraise'] = $appraise;
            }
            $appraevalu = $this->OrderModel->isUpdate()->save($data);
            if (!$appraevalu) {
                $this->error('评价失败请重新评价');
                exit;
            } else {
                $this->success('评价成功', '/user/order/index', $data);
                exit;
            }
        }
    }

    // 收货
    public function receiving()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0);
            $userid = $this->request->param('userid', 0);
            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }
            $where = [
                'id' => $id,
                'userid' => $userid
            ];
            // 退货订单
            $receivorder = $this->OrderModel->where($where)->find();
            if (!$receivorder) {
                $this->error('订单不存在收货失败');
                exit;
            };
            $data = [
                'id' => $id,
                'status' => 3
            ];
            $result = $this->OrderModel->isupdate()->save($data);
            if (!$result) {
                $this->error('收货失败');
                exit;
            } else {
                $this->success('收货成功');
                exit;
            }
        }
    }

    //充值/退货
    public function ExamineInvestReturnGoods()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            // 充值状态
            $recharg = $this->request->param('recharg', false);
            // 充值金额
            $rechargeamount = $this->request->param('rechargeamount', '');
            // 退货状态
            $returngoods = $this->request->param('return', false);
            // 是否有该用户
            $userinfo = $this->UserModel->find($userid);
            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            // 充值
            if ($recharg) {
                // 开启事务
                $this->PayModel->startTrans();

                $data = [
                    'userid' => $userid,
                    'point' => $rechargeamount,
                    'content' => '用戶充值',
                    'status' => 0
                ];
                $paychange = $this->PayModel->save($data);
                if (!$paychange) {
                    $paychange = $this->PayModel->save($data);
                    $this->error('充值失败');
                    $this->PayModel->rollback();
                    exit;
                } else {
                    $this->RecordModel->commit();
                    $this->success('充值成功!将于2-3个工作日到账');
                    exit;
                }
            }
            // 退货
            if ($returngoods) {
                // 订单id
                $id = $this->request->param('id', 0);

                $where = [
                    'id' => $id,
                    'userid' => $userid
                ];
                // 退货订单
                $returnorder = $this->OrderModel->where($where)->find();
                if (!$returnorder) {
                    $this->error('订单不存在退货失败');
                    exit;
                };

                // 是否已收货
                if($returnorder->status == 3){
                    // 订单是否超过7天超过静止退货
                    $starttime = strtotime($returnorder->createtime);
                    $returntime = time();
                    $ApplicationReturnTime = intval(bcsub($returntime,$starttime)/86400);
                    if($ApplicationReturnTime >= 7){
                        $this->error('订单已超过7天无法退货');
                        exit;
                    }
                }
                // 是否有消费记录
                $recordwhere = [
                    'userid' => $userid,
                    'state' => 5,
                    'createtime' => strtotime($returnorder->createtime),
                ];
                $consumption = $this->RecordModel->where($recordwhere)->find();
                if (!$consumption) {
                    $this->error('无消费记录退货失败');
                    exit;
                }

                // 开启事务
                $this->OrderModel->startTrans();
                $this->RecordModel->startTrans();

                // 更改订单状态
                $orderstatus = $this->OrderModel->isUpdate()->save(['id' => $id, 'status' => -1]);

                // 更改用户消费记录
                $updateconsump = $this->RecordModel->where($recordwhere)->update(['state' => -1]);

                // 返还退货金额
                if (!$orderstatus && !$updateconsump) {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error('退货失败');
                    exit;
                } else {
                    $this->OrderModel->commit();
                    $this->RecordModel->commit();
                    $this->success('退货成功!将于2-3个工作日到账');
                    exit;
                }
            }
        }
    }
}
